package fork;

import java.util.concurrent.ForkJoinPool;
import java.util.concurrent.RecursiveTask;

public class ForkJoinDemo {

    public static void main(String[] args) {

        long t1 = System.currentTimeMillis();
        int n = 50;

//        Integer result = dtfb(n);
        long result = dtfb2(n);
//        Integer result = fbForkJoin(n);
        // 输出结果
        System.out.println("result:" + result);

        System.out.println("use time:" + (System.currentTimeMillis() - t1) / 1000f);

    }

    public static long dtfb(int n) {
        if (n <= 1)
            return n;
        return dtfb(n - 1) + dtfb(n - 2);
    }

    public static long dtfb2(int n) {

        long[] array = new long[n];
        array[0] = 1L;
        array[1] = 1L;

        for (int i = 2; i < n; i++) {
            array[i] = array[i - 1] + array[i - 2];
        }

        return array[n - 1];
    }

    public static Integer fbForkJoin(int n) {
        // 创建分治任务线程池
        ForkJoinPool fjp =
                new ForkJoinPool(6);

        // 创建分治任务
        Fibonacci fib =
                new Fibonacci(n);

        // 启动分治任务
        Integer result =
                fjp.invoke(fib);

        return result;

    }

    // 递归任务
    static class Fibonacci extends
            RecursiveTask<Integer> {
        final int n;

        Fibonacci(int n) {
            this.n = n;
        }

        @Override
        protected Integer compute() {
            if (n <= 1) {
//                System.out.println("end:" + n);
                return n;
            }

            Fibonacci f1 =
                    new Fibonacci(n - 1);
            // 创建子任务
            f1.fork();
//            System.out.println("fork:" + (n - 1));
            Fibonacci f2 =
                    new Fibonacci(n - 2);
            // 等待子任务结果，并合并结果
            int count = f2.compute() + f1.join();
//            System.out.println("count: " + count);
            return count;
        }

    }


}
